<template>
	<view>
		<!-- <view class="alert">
			<uni-notice-bar single color="#f56c6c" background-color="#fef0f0" :text="titleSingle" />
		</view> -->
		<!-- 商品信息（封面加轮播图） -->
		<view class="card" style="margin-top: 40rpx;padding: 10px 10px 0px;">
			<view class="product-title">基础信息</view>
			<view style="display: flex;flex-flow: row wrap;">
				<u-upload style="flex: none;" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1"
					:maxCount="1" uploadText="封面图"></u-upload>
				<u-upload style="flex: none;" :fileList="fileList2" @afterRead="afterRead" @delete="deletePic" name="2"
					multiple :maxCount="9" uploadText="轮播图"></u-upload>
			</view>
			<view>
				<u--form labelPosition="left" :model="formModel" :rules="rules" ref="uForm">
					<u-form-item label="商品名称" prop="productDetail.name" required labelWidth="80" ref="item1">
						<u--input v-model="formModel.productDetail.name" :disabled="type !== ''" :disabledColor="'#fff'"
							:color="(type !== '' ? '#ccc' : '#000')" placeholder="请输入" border="none"></u--input>
					</u-form-item>
					<u-form-item label="商品类别" @click="type !== ''?null:openCategoryClass(1)" required
						prop="productDetail.largeCategoryCode" labelWidth="80" ref="item1">
						<u--input v-model="largeCategoryName" placeholder="请选择" :disabled="type != ''" disabledColor="#fff"
							:color="(type !== '' ? '#ccc' : '#000')" border="none"></u--input>
						<!-- <u-icon v-if="type == ''" slot="right" name="arrow-right" @click="openCategoryClass(1)"></u-icon> -->
						<text v-if="type == ''" class='iconfont icon-xiangyou' @click="openCategoryClass(1)"></text>
					</u-form-item>

					<u-form-item label="商品分类" @click="type !== ''?null:toGoodsClass(1)" required
						prop="productDetail.categoryId" labelWidth="80" ref="item1">
						<u--input v-model="categoryname" placeholder="请选择" :disabled="type != ''" disabledColor="#fff"
							:color="(type !== '' ? '#ccc' : '#000')" border="none"></u--input>
						<u-icon v-if="type == ''" slot="right" name="arrow-right" @click="toGoodsClass(1)"></u-icon>
					</u-form-item>

					<u-form-item label="品牌" @click="type !== ''?null:toCategoryBrand(1)" required
						prop="productDetail.brandId" labelWidth="80" ref="item1">
						<u--input v-model="brandName" placeholder="请选择" :disabled="type != ''" disabledColor="#fff"
							:color="(type !== '' ? '#ccc' : '#000')" border="none"></u--input>
						<u-icon v-if="type == ''" slot="right" name="arrow-right"
							@click="type !== ''?null:toCategoryBrand(1)"></u-icon>
					</u-form-item>
					<!-- <u-form-item label="单位" prop="productDetail.unitName" labelWidth="80" ref="item1">
						<u--input v-model="formModel.productDetail.unitName" placeholder="请输入"
							border="surround"></u--input>
					</u-form-item> -->
					<!-- <u-form-item label="关键字" prop="productDetail.keyword" labelWidth="80" ref="item1">
						<view style="display: flex;flex-wrap:wrap;align-items: center;">
							<u-tag v-for="(name,index) in keywords" :key="index" style="flex-direction: row;"
								:text="name" :borderColor="bgColor" :color="bgColor" closable plain
								@close="keywords.splice(index, 1);"></u-tag>
							<view style="margin-left: 10px;">
								<u-icon @click="showAddParam(1)" name="plus-circle" :color="bgColor" size="24"></u-icon>
							</view>
						</view>
					</u-form-item> -->
				</u--form>
				<!-- 商品名称 -->
				<!-- 平台分类 -->
				<!-- 商户分类 -->
				<!-- 品牌 -->
				<!-- 单位 -->
				<!-- 关键字 -->
			</view>
		</view>

		<view v-if="inputValid1 && inputValid2 && inputValid3&& inputValid4">
			<!-- 规格参数 -->
			<view class="card left-fill-card" style="padding: 10px; ">
				<view class="product-title" style="display: flex;justify-content: space-between;">
					<view>详细信息 </view>
					<view v-if="productInfoParam != null || type == 'edit'" @click="goInformation('edit')"
						:style="{color:bgColor}">
						<span style="font-size: 15px;">进行修改信息</span>
						<uni-icons type="forward" color="#ccc" size="20"></uni-icons>
					</view>
				</view>
				<view style="background-color: #f5f5f5;border-radius: 10px;border:#ddd solid 1px;">
					<!-- 参数列表 -->
					<view style="min-height: 50px;font-size: 16px;line-height: 50px;padding:0 10px;">
						<view style="display: flex;align-items: center;" v-for="(value,key,index) in specParamMap">
							<view style="flex: 1;">
								<view style="display: block;line-height: normal;">
									{{key}}
								</view>
							</view>
							<view style="flex: 2;">
								<view style="display: flex;justify-content: space-between;">
									<view>{{value ? value : '-'}}</view>
									<!-- <u-icon @click="deleteSpecParam(key)" name="close" color="#666" size="14"
										bold></u-icon> -->
								</view>
							</view>
						</view>
						<!-- <view style="display: flex;justify-content: center;">
							<u-icon name="plus" :color="bgColor" size="16" bold></u-icon>
							<view @click="showAddParam(2)" style="margin-left: 6px;font-weight:bold;"
								:style="{color:bgColor}">添加信息</view>
						</view> -->
						<view v-if="(productInfoParam == '' && id == '') || (productInfoParam == null  && id == '')"
							style="display: flex;justify-content: center;">
							<u-icon name="plus" :color="bgColor" size="16" bold></u-icon>
							<view @click="goInformation('add')" style="margin-left: 6px;font-weight:bold;"
								:style="{color:bgColor}">添加信息</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 规格属性 -->
			<view class="card right-fill-card" style="padding: 10px;">
				<view class="product-title">售卖规格</view>
				<view>
					<view
						style="min-height: 50px;font-size: 16px;line-height: 50px;padding:0 10px;background-color: #f5f5f5;border-radius: 10px;border:#ddd solid 1px;">
						<view style="display: flex;" v-for="(item,index) in skuArr" :key="index">
							<view style="flex: 1;">{{attrKey + (index+1)}}</view>
							<view style="flex: 2;">
								<view style="display: flex;justify-content: space-between;">
									<view>{{item.sku}}</view>
									<u-icon v-if="item.id != ''" name="edit-pen" color="#666" size="24" bold
										@click="toProductAttr('edit',item,index)"></u-icon>
									<!-- <u-icon v-if="isShowAttr" @click="delAttrTable(item,index)" name="close" color="#666" size="14"
										bold></u-icon> -->
								</view>
							</view>
						</view>
						<!-- <view v-if="isShowAttr || type == 'add' ? true :false" -->
						<view v-if="type == 'add' || type == ''" style="display: flex;justify-content: center;">
							<u-icon name="plus" :color="bgColor" size="16" bold></u-icon>
							<view style="margin-left: 6px;font-weight:bold;" :style="{color:bgColor}"
								@click="toProductAttr('add')">添加规格</view>
						</view>
					</view>
				</view>

			</view>

			<!-- 商品简介 -->
			<view class="card" style="padding: 10px">
				<view class="product-title">卖点描述</view>
				<u--textarea v-model="formModel.productDetail.intro" :color="(type !== '' ? '#ccc' : '#000')"
					style="background-color: #f5f5f5 ;" placeholder="请填写..." count maxlength="300"
					height="50"></u--textarea>
			</view>

			<!-- 运费及保障服务 -->
			<!-- <view class="card" style="padding: 10px;">
				<view class="product-title">运费及保障服务</view>
				运费模板
				<view style="margin: 20px 0 10px 0;">
					<view style="display: flex;">
						<view style="flex: 1;">
							<view style="font-size: 16px;">运费模板：</view>
						</view>
						<view style="flex: 3;">
							<picker @change="selectTemplatesChange" :value="selectTemplatesIndex" range-key="name"
								:range="shippingTemplatesList">
								<view style="display: flex;justify-content: space-between;font-size: 15px;">
									<view v-if="shippingTemplatesList[selectTemplatesIndex]">
										{{shippingTemplatesList[selectTemplatesIndex].name}}
									</view>
									<view v-else style="color:#c0c4cc;">请选择</view>
									<u-icon name="arrow-right" color="#666" size="16"></u-icon>
								</view>
							</picker>
						</view>
					</view>
				</view>

				保障服务
				<view>
					<view style="display: flex;">
						<view style="flex: 1;">
							<view style="font-size: 16px;">保障服务：</view>
						</view>
						<view style="flex: 3;">
							<view style="display: flex;flex-wrap:wrap;align-items: center;">
								<u-tag v-for="(item,index) in guaranteeItems" :key="index" style="flex-direction: row;"
									:text="item.name" :bgColor="bgColor" type="warning" closable
									@close="guaranteeItems.splice(index, 1)"></u-tag>
								<view style="margin-left: 10px;">
									<picker @change="selectGuaranteeChange" range-key="name"
										:range="productGuaranteeList">
										<u-icon name="plus-circle" :color="bgColor" size="24"></u-icon>
									</picker>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view> -->
		</view>


		<!-- 商品详情（图） -->
		<view style="height: 100px;"></view>

		<view style="position: fixed;bottom: 0px;width: 100%;padding: 10px;background-color: #FFF;z-index: 999;">
			<button class="bg_color plain_bgColor"
				style="font-weight: bold;border-radius: 10px;padding: 20rpx;color: #fff;" :loading="loading"
				:style="{color:bgColor}" @click="submitProduct">提交</button>
		</view>
		<!-- 组件部分------- -->
		<u-toast ref="uToast"></u-toast>

		<!-- 商品类别 -->
		<tui-drawer mode="bottom" :visible="showGroupCategory" @close="showGroupCategory = false">
			<view class="u-demo-block2 ensure">
				<view class="titleRight">选择商品类别<text @click="close" class="iconfont icon-guanbi5"></text></view>
				<view style="margin: 10px 0 10px 0">
					<!-- <view class="sku-select">
						<view class="uni-flex uni-row" style="-webkit-flex-wrap: wrap;flex-wrap: wrap;">
							<view class="flex-text"
								:class='item.name == largeCategoryName? "right-class-active" :""'
								v-for="(item,index) in largeCategoryData" :key="index" @click='tapAttr(item)'>
								{{item.name}}
							</view>
						</view>
					</view> -->
					<radio-group v-model="categoryValue1" @change="radioChange">
						<label
							style="display: flex;flex-direction: row;margin: 20rpx;border-bottom: 1px solid #eee;padding: 20rpx 0;"
							v-for="(item, index) in largeCategoryData" :key="index">
							<view>
								<radio :value="item.code" />
							</view>
							<view style="line-height: 19px;">{{item.name}}</view>
						</label>
					</radio-group>
				</view>
			</view>
			<view style="height: 120rpx;">
				
			</view>
			<!-- </u-popup> -->
		</tui-drawer>

		<!-- 添加关键字，规格参数，弹窗 -->
		<tui-drawer mode="bottom" :visible="addParamDrawer.show" @close="addParamDrawer.show = false">
			<view class="ensure">
				<view @click="addParamDrawer.show = false" class="title">添加{{addParamDrawer.title}}<text
						class="iconfont icon-guanbi5"></text></view>
				<view style="height: auto;padding-top: 20rpx; margin: 0 40rpx;">
					<view>
						<view style="display: flex;">
							<view style="flex: 1;">
								<view style="font-size: 16px;">{{addParamDrawer.title}}：</view>
							</view>
							<view style="flex: 3;">
								<view style="display: flex;flex-wrap:wrap;align-items: center;">
									<u--input v-model="addParamDrawer.name" placeholder="请输入"
										border="surround"></u--input>
								</view>
							</view>
						</view>
						<view v-if="addParamDrawer.type == 2" style="margin-top: 40rpx;display: flex;">
							<view style="flex: 1;">
								<view style="font-size: 16px;">参数内容：</view>
							</view>
							<view style="flex: 3;">
								<view style="display: flex;flex-wrap:wrap;align-items: center;">
									<u--input v-model="addParamDrawer.value" placeholder="请输入"
										border="surround"></u--input>
								</view>
							</view>
						</view>
					</view>
					<view style="width: 100%;margin-top: 80rpx;">
						<button @click="addParamClick" class="bg_color plain_bgColor" :style="{color:bgColor}"
							style="font-weight: bold;border-radius: 10px;padding: 20rpx;" :color="bgColor">添加</button>
					</view>
				</view>
			</view>
		</tui-drawer>

	</view>
</template>

<script>
	import {
		brandlistApi,
	} from '@/api/category.js';
	import {
		shippingTemplatesList
	} from '@/api/logistics.js';
	import {
		productUpdateApi,
		productCreateApi,
		categoryApi,
		productGuaranteeApi,
		productDetailApi,
		removeProductApi,
		getProductLargeApi
	} from '@/api/product.js';

	import animationType from '@/utils/animationType.js'
	import {
		setThemeColor
	} from '@/utils/setTheme.js'
	import tuiDrawer from '@/components/tui-drawer/index.vue';
	import image from '../../../uni_modules/uview-ui/libs/config/props/image';
	let app = getApp();
	let _this = undefined;
	export default {
		components: {
			tuiDrawer,
		},
		data() {
			return {
				bgColor: "#ffffff",
				theme: app.globalData.theme,
				titleSingle: '多规格商品请前往电脑端进行小规格的添加，删除操作',
				id: 0, //商品ID
				type: '', // 修改?添加类型
				attrKey: "规格", //默认的规格key名称
				specParamMap: {}, //规格参数
				sliderImages: [], //轮播图列表
				productCredentials: [], //资质图片
				skuArr: [], //商品规格
				fileList1: [
					// {
					// 	url:"https://p3.ssl.qhimg.com/t0137f6f23e234057d6.webp",
					// }
				], //商品封面图
				fileList2: [
					// {
					// 	url:"https://p4.ssl.qhimg.com/dr/90_0_85/t01ef6a992a4e4ce63c.webp",
					// }
				], //商品轮播图
				keywords: [], //关键词列表
				guaranteeItems: [], //选择的保障服务对象列表


				productGuaranteeList: [], //所有保障服务

				selectTemplatesIndex: null, //选择的运费模板
				shippingTemplatesList: [], //所有运费模板

				categoryTree: [], //平台商品分类树
				citygoryTree: [], //城市缓存树
				formModel: {
					productDetail: {
						image: "", //商品图片
						sliderImage: "", //轮播图
						cateId: "0", //商户商品分类id
						// isSub: "false", //是否单独分佣
						attr: [], //商品属性ProductAttrAddRequest
						attrValue: [], //商品属性详情

						name: "", //商品名称
						intro: "", //商品简介
						brandId: "", //品牌
						categoryId: "", //平台商品分类id
						// unitName: "", //单位
						// keyword: "", //关键字
						specParam: "", //规格参数
						largeCategoryCode:"", //商品类别
						// guaranteeIds: "", //保障服务ids
						// tempId: null, //运费模板ID
						specType: true, //多规格
					}, //商品详情
				},
				rules: {
					'productDetail.name': {
						type: 'string',
						required: true,
						message: '请填写商品名称',
						trigger: ['blur', 'change']
					},
					'productDetail.largeCategoryCode': {
						type: 'string',
						required: true,
						message: '请填写商品类别',
						trigger: ['blur', 'change']
					},
					'productDetail.categoryId': {
						type: 'number',
						required: true,
						message: '请填写商品分类',
						trigger: ['blur', 'change']
					},
					'productDetail.brandId': {
						type: 'number',
						required: true,
						message: '请填写商品品牌',
						trigger: ['blur', 'change']
					},
					// 'productDetail.unitName': {
					// 	type: 'string',
					// 	required: true,
					// 	message: '请填写商品单位',
					// 	trigger: ['blur', 'change']
					// },

				},
				//---组件
				addParamDrawer: {
					show: false, //弹窗显隐
					title: '添加关键字', //title
					type: 1, //类型
					name: '', //名称
					value: '', //值
				},
				brandName: '',
				brandData: [], //品牌列表
				categoryname: '', //分类名称，
				deleteData: [], //删除的小sku
				rawSkuArr: [], //原始数据
				isShowAttr: true,
				productInfoParam: null, //深拷贝详细信息数据
				inputValid1: false,
				inputValid2: false,
				inputValid3: false,
				inputValid4:false,
				loading: false,
				// --------商品大类--------
				largeCategoryData:[],
				largeCategoryName:'',
				showGroupCategory:false, //商品大类弹窗
				categoryValue1:'',
			};
		},
		async onLoad(options) {
			this.bgColor = setThemeColor();
			console.log('options', options)
			if (options.id) {
				this.id = options.id;
				this.type = options.type;
				if (options.type == 'edit') {
					uni.setNavigationBarTitle({
						title: '修改商品'
					});
				} else {
					uni.setNavigationBarTitle({
						title: '添加规格'
					});
				}
			}
			// 初始化表单选项数据
			// 分类，品牌，保障服务，运费模板等
			// 加载保障服务，
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			this.getBrand();
			await this.getCategoryTree();
			// await this.getProductGuarantee();
			// await this.getShippingTemplatesList();
			uni.hideLoading();
			if (options.id) {
				//加载商品详情
				this.getProductDetail();
			}else{
				this.getLargeList();
			}
			uni.$on('showMessageTherFun', (brandObj) => {
				this.brandName = brandObj.brandName;
				this.formModel.productDetail.brandId = brandObj.brandId;
			});
			uni.$on('productClassTherFun', (productClass) => {
				this.categoryname = productClass.name;
				this.formModel.productDetail.categoryId = productClass.id;
			});
		},
		watch: {
			'formModel.productDetail.name': function(newVal, oldVal) {
				this.inputValid1 = false;
				if (newVal != '') {
					this.inputValid1 = true;
				}
			},
			'formModel.productDetail.largeCategoryCode': function(newVal, oldVal) {
				this.inputValid4 = false;
				if (newVal != '') {
					this.inputValid4 = true;
				}
			},
			brandName: function(newVal, oldVal) {
				this.inputValid2 = false;
				if (newVal != '') {
					this.inputValid2 = true;
				}
				if (newVal !== oldVal) {
					this.productInfoParam = null; //选完类别后，回来清空上次所填的商品详情
					if (this.id == '') {
						this.specParamMap = {};
						this.skuArr = [];
					}

				}
			},
			categoryname: function(newVal, oldVal) {
				this.inputValid3 = false;
				if (newVal != '') {
					this.inputValid3 = true;
				}
				if (newVal !== oldVal) {
					this.productInfoParam = null; //选完类别后，回来清空上次所填的商品详情
					if (this.id == '') {
						this.specParamMap = {};
						this.skuArr = [];
					}
				}
			}
		},

		methods: {
			// 获取产品大类列表
			getLargeList(){
				getProductLargeApi().then((res) => {
					this.largeCategoryData = res.data;
				})
			},
			radioChange(n) {
				let radioValue = n.detail.value;
				this.categoryValue1 = radioValue;
				this.formModel.productDetail.largeCategoryCode = radioValue;
				for(let i = 0;i<this.largeCategoryData.length;i++){
					if(this.largeCategoryData[i].code == radioValue){
						this.largeCategoryName = this.largeCategoryData[i].name
					}
				};
				this.showGroupCategory = false;
			},
			//获取品牌id
			getBrand() {
				brandlistApi(this.brandForm).then((res) => {
					this.brandData = res.data.records.map(({
						id,
						name
					}) => ({
						id,
						name
					}));
				});
			},

			/** 
			 * 更新详情属性
			 */
			spInformationFun(productInfoParam) {
				console.log('productInfoParam', productInfoParam)
				let that = this;
				that.productInfoParam = JSON.parse(JSON.stringify(productInfoParam)); //深拷贝数据
				if (productInfoParam.isShelfLife == '1') {
					if (productInfoParam.shelfLifeUnit == '月') {
						productInfoParam.isShelfLife = `${productInfoParam.shelfLifeNumber}` + '个' +
							`${productInfoParam.shelfLifeUnit}`
					} else {
						productInfoParam.isShelfLife =
							`${productInfoParam.shelfLifeNumber}${productInfoParam.shelfLifeUnit}`
					}
				} else if (productInfoParam.isShelfLife == '0') {
					productInfoParam.isShelfLife = '无'
				}
				// 定义属性名映射表
				const keyMap = {
					isDomestic: '国产出口',
					modeOfTransport: '运输方式',
					storageMode: '贮存方式',
					isShelfLife: '保质期',
					factoryLabelAddress: '商品包装标注工厂地址',
					factoryLabelName: '商品包装标准工厂名称',
					foodLabels: '食材标签',
					foodOuterPack: '商品外包装名称',
					skuNoteBarcode: '备忘SKU条码',
					addressNode: '商品包装标注产地',
					// manufactureDate: '生产日期',
				};
				const newObj = this.renameKeys(productInfoParam, keyMap);
				delete newObj.shelfLifeNumber;
				delete newObj.shelfLifeUnit;
				that.specParamMap = newObj;
			},
			// 修改属性名的方法
			renameKeys(obj, keyMap) {
				return Object.keys(obj).reduce((acc, key) => {
					const newKey = keyMap[key] || key;
					acc[newKey] = obj[key];
					return acc;
				}, {});
			},
			//更新规格参数
			otherFun(productAttrParam) {
				console.log('productAttrParam', productAttrParam)
				if (productAttrParam) {
					//添加编辑规格参数
					if (productAttrParam.index == undefined && productAttrParam.type == "add") { //添加
						this.skuArr.push(productAttrParam.data);
					} else { //编辑
						for (let i = 0; i < this.rawSkuArr.length; i++) {
							if (this.rawSkuArr[i].id == productAttrParam.data.id) {
								// 检查指定属性在两个对象之间的值是否不同
								if (this.rawSkuArr[i].sku !== productAttrParam.data.sku || this.rawSkuArr[i].specUnit !==
									productAttrParam.data.specUnit || this.rawSkuArr[i].image !== productAttrParam.data
									.image) {
									productAttrParam.data.sign = 0; // 如果属性值不同，给 obj2 添加修改标识
								} else {
									productAttrParam.data.sign = 3; // 如果属性值相同，确保修改标识为 false
								}
							}
						};
						this.skuArr.splice(productAttrParam.index, 1, productAttrParam.data)
					}
				}
			},


			//提交商品
			submitProduct() {
				// 更新商品标识
				let isUpdate = parseFloat(this.id) > 0;
				// 校验数据
				let that = this;
				this.$refs.uForm.validate().then(res => {
					uni.$u.toast('1校验通过');
					//规格参数,规格属性,商品简介,运费模板，保障服务，商品详情*
					if (
						that.fileList1.length == 0
					) {
						uni.$u.toast('请上传封面图！');
						return;
					} else if (that.fileList2.length == 0) {
						uni.$u.toast('请上传轮播图片！');
						return;
					}
					if (
						that.fileList1.length == 0 ||
						that.fileList2.length == 0 ||
						// that.keywords.length == 0 ||
						Object.keys(that.specParamMap).length == 0 ||
						that.skuArr.length == 0 ||
						that.formModel.productDetail.intro == null || that.formModel.productDetail.intro.length ==
						0
						// ||
						// that.selectTemplatesIndex == null
						// ||that.guaranteeItems.length == 0
					) {
						uni.$u.toast('请填写完整商品信息！');
						return;
					}
					uni.$u.toast('2校验通过');
					// 同步表单数据
					that.getFormValue();
					// 提交表单
					uni.$u.toast('3提交表单');
					if (this.deleteData.length) {
						for (let item of this.deleteData) {
							this.skuArr.push(item); // 添加被删除的商品，带回
						}
					}
					that.loading = true;
					// console.log('that.formModel.productDetail',that.formModel.productDetail)
					let api = isUpdate ? productUpdateApi : productCreateApi;
					uni.showLoading({
						title: '保存中'
					});
					api(that.formModel.productDetail).then(res => {
							if (res.code == 200) {
								uni.$u.toast('保存成功！');
								//关闭当前页面
								setTimeout(() => {
									uni.navigateBack()
								}, 500);
								that.loading = false;
							} else {
								console.log(res.msg);
								uni.$u.toast('保存失败！');

							}
						})
						.catch((res) => {
							console.log(res);
							uni.$u.toast('保存失败！' + res);
							that.loading = false;
						})

				}).catch(errors => {
					console.log("submitProduct error", errors);
					uni.$u.toast('请填写完整商品信息！');
				})
			},

			//获取表单需要的值
			getFormValue() {
				let product = this.formModel.productDetail;
				product.image = this.fileList1[0].url;
				product.sliderImage = JSON.stringify(this.fileList2.map(item => item.url));
				// product.keyword = this.keywords.join(',');
				if(this.specParamMap.isShelfLife == '无'){
					this.specParamMap.isShelfLife = '99年'
				};
				product.specParam = JSON.stringify(this.specParamMap);
				// product.tempId = this.shippingTemplatesList[this.selectTemplatesIndex].id;
				// const guaranteeIdsList = this.guaranteeItems.map(obj => obj.id);
				// product.guaranteeIds = guaranteeIdsList.join(',');
				if (product.id == undefined) {
					this.getInformation();
					// console.log('详细信息保质期')
				}

				// 同步 规格信息
				product.specType = true; //设置多规格
				// --------
				// attr | attrValue 
				// 验证是添加还是更新
				let attr = product.attr;
				let attrValuesList = [];
				// 校验skuArr和attrValue是否一个对象
				product.attrValue = this.skuArr;
				if (attr.length == 1) {
					this.attrKey = attr[0].attrName;
				};
				for (let s of this.skuArr) {
					let av = JSON.parse(s.attrValue);
					attrValuesList.push(av[this.attrKey]);
				};
				let attrValues = attrValuesList.join(',');
				if (attr.length == 0) {
					attr.push({
						attrName: this.attrKey,
						attrValues: attrValues
					});
				} else if (attr.length == 1) {
					attr[0].attrValues = attrValues;
				} else {
					attr = attr;
				};

				this.$set(this.formModel, 'productDetail', product);
			},
			// 过滤数据，将详细信息保质期等内容，放入attrValue中，
			getInformation() {
				let InfoParam = {};
				if (this.productInfoParam == '' || this.productInfoParam == undefined) {
					let newObj = {};
					const keyMap = {
						国产出口: 'isDomestic',
						运输方式: 'modeOfTransport',
						贮存方式: 'storageMode',
						保质期: 'isShelfLife',
						商品包装标注工厂地址: 'factoryLabelAddress',
						商品包装标准工厂名称: 'factoryLabelName',
						食材标签: 'foodLabels',
						商品外包装名称: 'foodOuterPack',
						备忘SKU条码: 'skuNoteBarcode',
						商品包装标注产地: 'addressNode',
						// 生产日期: 'manufactureDate',
					};
					newObj = this.renameKeys(this.specParamMap, keyMap);
					if (newObj.isShelfLife != '无') {
						const {
							shelfLifeNumber,
							shelfLifeUnit
						} = this.separateDigitsAndCharactersInString(newObj.isShelfLife);
						newObj.shelfLifeNumber = shelfLifeNumber;
						newObj.shelfLifeUnit = shelfLifeUnit;
						newObj.isShelfLife = '1'
					} else {
						newObj.isShelfLife = '0'
					};
					InfoParam = newObj;
				} else {
					InfoParam = this.productInfoParam;
				}
				if (InfoParam.isShelfLife == "无" || InfoParam.isShelfLife == '0') {
					InfoParam.isShelfLife = '0';
				} else {
					InfoParam.isShelfLife = '1';
				};
				let infoProduct = {
					isShelfLife: InfoParam.isShelfLife,
					shelfLifeNumber: InfoParam.shelfLifeNumber,
					shelfLifeUnit: InfoParam.shelfLifeUnit,
					modeOfTransport: InfoParam.modeOfTransport,
					storageMode: InfoParam.storageMode
					// manufactureDate: InfoParam.manufactureDate
				};
				let modifiedArray = this.skuArr.map(item => {
					return {
						...item,
						specUnit: JSON.stringify(Object.assign(JSON.parse(item.specUnit), infoProduct))
					}
				})
				this.skuArr = modifiedArray;
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					if (result == null) {
						uni.showToast({
							title: "上传失败",
							icon: "none",
						})
						this.deletePic(event.index, 1);
						break;
					}
					let newStatus = {
						status: 'success',
						message: '上传成功',
						url: result,
					}
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, newStatus))
					fileListLen++
				}
			},
			uploadFilePromise(filePath) {
				return this.$util.uploadFilePromise(filePath, {
					url: 'upload/image',
					name: "multipart", //固定 multipart
					model: "product", //模块 用户user,商品product,微信wechat,news文章
					pid: 1, //分类ID 0编辑器,1商品图片,2拼团图片,3砍价图片,4秒杀图片,5文章图片,6组合数据图,7前台用户,8微信系列
					count: 1
				});
			},
			separateDigitsAndCharactersInString(str) {
				const matches = str.match(/(\d+)(\D+)/);
				if (matches && matches.length === 3) {
					const shelfLifeNumber = matches[1];
					const shelfLifeUnit = matches[2];
					return {
						shelfLifeNumber,
						shelfLifeUnit
					};
				} else {
					// 如果无法匹配到数字和字符，则返回原始字符串
					return {
						shelfLifeNumber: str,
						shelfLifeUnit: ''
					};
				}
			},
			// 详情信息
			goInformation(type) {
				let newObj = {};
				if (this.id != '') {
					let that = this;
					// 定义属性名映射表
					const keyMap = {
						国产出口: 'isDomestic',
						运输方式: 'modeOfTransport',
						贮存方式: 'storageMode',
						保质期: 'isShelfLife',
						商品包装标注工厂地址: 'factoryLabelAddress',
						商品包装标准工厂名称: 'factoryLabelName',
						食材标签: 'foodLabels',
						商品外包装名称: 'foodOuterPack',
						备忘SKU条码: 'skuNoteBarcode',
						商品包装标注产地: 'addressNode',
						// 生产日期: 'manufactureDate',
					};
					newObj = this.renameKeys(this.specParamMap, keyMap);
					if (newObj.isShelfLife != '无') {
						const {
							shelfLifeNumber,
							shelfLifeUnit
						} = this.separateDigitsAndCharactersInString(newObj.isShelfLife);
						newObj.shelfLifeNumber = shelfLifeNumber;
						newObj.shelfLifeUnit = shelfLifeUnit;
						newObj.isShelfLife = '1'
					} else {
						newObj.isShelfLife = '0'
					};
				}

				let pageData = {};

				if (this.id != '') {
					pageData = newObj;
				} else {
					pageData = this.productInfoParam;
				}
				// 页面传值 规格信息item，并可返回
				this.goPage(`/pages/product/spInformation/spInformation?type=${type}`,
					(res) => {
						// 通过eventChannel向被打开页面传送数据
						res.eventChannel.emit('productInfo', {
							// data: this.productInfoParam,
							data: pageData,
							type: type,
							from: "saveProduct",
						})
					});
			},
			// 编辑规格信息
			toProductAttr(type, item, index) {
				let isHasId = false;
				if (item != undefined && item.id) {
					type = 'edit';
				} else {
					type = "add";
					if (this.id != undefined && this.id != 0) {
						isHasId = true; //有id
					} else {
						isHasId = false; //无id
					}
				}
				// 页面传值 规格信息item，并可返回
				this.goPage(`/pages/product/saveProductAttr/saveProductAttr?type=${type}`,
					(res) => {
						// 通过eventChannel向被打开页面传送数据
						res.eventChannel.emit('productAttr', {
							index: index,
							data: item,
							type: type,
							from: "saveProduct",
							attrKey: this.attrKey,
							isHasId: isHasId
							// unitName: this.formModel.productDetail.unitName,
						})
					}
				);
			},
			// 商品类别
			openCategoryClass() {
				//页面传值
                this.showGroupCategory = true;
			},
			toGoodsClass(item) {
				//页面传值
				this.goPage(`/pages/product/productGoodsClass/productGoodsClass?data=${item}`)
			},
			toCategoryBrand(item) {
				//页面传值
				this.goPage(`/pages/categoryTable/categoryBrand/categoryBrand?data=${item}`)
			},
			goPage(url, success) {
				uni.navigateTo({
					animationType: animationType.type,
					animationDuration: animationType.duration,
					url,
					success: success
				})
			},
			// ------------------



			// ------------------
			//查询商品详情
			async getProductDetail() {
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				let that = this;
				await productDetailApi(this.id).then(res => {
					if (res.code == 200) {
						that.formModel.productDetail = res.data;
						that.skuArr = res.data.attrValue;
						for (let item of that.skuArr) {
							item.sign = 3 // 0修改，1删除，2添加，3没动
						};
						if (that.formModel.productDetail.attr.length == 1) {
							this.attrKey = that.formModel.productDetail.attr[0].attrName;
						} else {
							this.isShowAttr = false; //多规格不展示添加功能，不可添加，不可删除
						}
						that.rawSkuArr = JSON.parse(JSON.stringify(res.data.attrValue));
						// 格式化商品参数 specParam
						//商品规格参数
						that.$set(that, 'specParamMap', JSON.parse(res.data.specParam));
						//商品轮播图
						that.$set(that, 'sliderImages', JSON.parse(res.data.sliderImage));
						// 检测报告图
						that.$set(that, 'productCredentials', JSON.parse(res.data.productCredential));

						//--------------解析商品数据为表单数据
						that.fileList1 = [{
							url: res.data.image
						}];
						for (let image of that.sliderImages) {
							that.fileList2.push({
								url: image
							});
						}
						// that.keywords = res.data.keyword.split(",");
						//初始化选择的保障服务列表
						// that.initProductGuaranteeSelect();
						//初始化商品选择的模板
						// that.initSelectTemplates();
					}
					uni.hideLoading();
					//分类的回显
					// for (let i = 0; i < this.categoryTree.length; i++) {
					// 	if (this.categoryTree[i].id == that.formModel.productDetail.categoryId) {
					// 		that.categoryname = this.categoryTree[i].name;
					// 		break;
					// 	} else {
					// 		that.categoryname = '未添加';
					// 	}
					// }
					that.categoryname = res.data.categoryName;

					//回显品牌名称
					if (this.brandData.length) {
						for (let i = 0; i < this.brandData.length; i++) {
							if (that.formModel.productDetail.brandId == this.brandData[i].id) {
								that.brandName = this.brandData[i].name;
								return;
							} else {
								that.brandName = '无品牌';
							}
						}
					} else {
						that.brandName = '无品牌';
					}


				}).catch(err => {
					console.log("getProductDetail error", err)
					uni.hideLoading();
				});
			},

			//查询所有保障服务
			async getProductGuarantee() {
				let res = await productGuaranteeApi();
				if (res.code == 200) {
					this.productGuaranteeList = res.data;
				}
			},
			//初始化选择的保障服务列表
			initProductGuaranteeSelect() {
				if (this.formModel.productDetail.guaranteeIds == null) {
					return;
				}
				for (let id of this.formModel.productDetail.guaranteeIds.split(',')) {
					let item = this.getProductGuaranteeById(id);
					if (item != null) {
						this.guaranteeItems.push(item);
					}
				}
			},
			getProductGuaranteeById(id) {
				for (let s of this.productGuaranteeList) {
					if (s.id == id) {
						return s;
					}
				}
				return null;
			},
			// ----
			//添加保障服务
			selectGuaranteeChange(e) {
				let item = this.productGuaranteeList[e.detail.value];
				if (this.guaranteeItems.includes(item)) {
					this.$refs.uToast.show({
						message: "重复添加",
					});
					return;
				}
				this.guaranteeItems.push(item);
			},
			//查询所有保障服务
			async getShippingTemplatesList() {
				let res = await shippingTemplatesList();
				if (res.code == 200) {
					this.shippingTemplatesList = res.data.list;
				}
			},


			//选择更改运费模板
			selectTemplatesChange(e) {
				this.selectTemplatesIndex = e.detail.value
				this.formModel.productDetail.tempId = this.shippingTemplatesList[e.detail.value].id;
			},
			//初始化商品选择的模板
			initSelectTemplates() {
				if (this.formModel.productDetail.tempId == null) {
					return;
				}
				for (var i = 0; i < this.shippingTemplatesList.length; i++) {
					if (this.shippingTemplatesList[i].id == this.formModel.productDetail.tempId) {
						this.selectTemplatesIndex = i;
					}
				}
			},



			//-----
			//查询平台端商品分类缓存树
			async getCategoryTree() {
				let res = await categoryApi();
				let that = this;
				if (res.code == 200) {
					// this.categoryTree = res.data;
					const result = [];
					for (const item1 of res.data) {
						for (const item2 of item1.childList) {
							for (const item3 of item2.childList) {
								result.push(item3);
							}
						}
					}
					this.categoryTree = result;
				}
			},


			//---
			//填出提添加参数框
			showAddParam(type) {
				this.addParamDrawer.type = type;
				this.addParamDrawer.title = type == 1 ? "关键字" : "规格参数";
				this.addParamDrawer.show = true;
			},
			addParamClick() {
				let name = this.addParamDrawer.name;
				let value = this.addParamDrawer.value;
				if (name.length == 0) {
					this.$refs.uToast.show({
						message: "名称不能为空",
					});
					return;
				}
				if (this.addParamDrawer.type == 1) {
					//添加关键字
					if (this.keywords.includes(name)) {
						this.$refs.uToast.show({
							message: "重复添加",
						});
						return;
					}
					this.keywords.push(name);
				} else {
					//添加规格参数
					if (value.length == 0) {
						this.$refs.uToast.show({
							message: "内容不能为空",
						});
						return;
					}
					this.specParamMap[name] = value;
				}

				this.addParamDrawer.name = "";
				this.addParamDrawer.value = "";
				this.addParamDrawer.show = false;
			},
			//删除规格参数
			deleteSpecParam(key) {
				const {
					[key]: removedProperty, ...objRest
				} = this.specParamMap;
				this.specParamMap = objRest;
			},
			// 删除表格中的属性
			delAttrTable(item, index) {
				let newItem = item
				newItem.sign = 1; //添加删除标识
				this.deleteData.push(item);
				this.skuArr.splice(index, 1);
			},
		}
	}
</script>

<style lang="scss">
	.bg_color {
		@include main_bg_color(theme);
	}

	.plain_bgColor {
		@include main_color(theme);
		@include main_bg_rgba_color(theme, 0.05);
		border: 1rpx solid;
	}

	.card {
		margin: 0 20rpx 20rpx 20rpx;
		background-color: #fff;
		border-radius: 20rpx;


	}

	.product-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 20rpx;
		margin-top: 10rpx;
	}

	.ensure {
		width: 100%;
		background-color: #fff;
		padding-bottom: 22rpx;
		padding-bottom: calc(22rpx+ constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
		padding-bottom: calc(22rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/

		.title {
			font-size: 36rpx;
			color: #282828;
			text-align: center;
			margin: 38rpx 0 36rpx 0;
			position: relative;

			.iconfont {
				position: absolute;
				right: 30rpx;
				top: 0;
				font-size: 36rpx;
			}
			
			.iconfontRight {
				position: absolute;
				right: 30rpx;
				top: 0;
				font-size: 30rpx;
				@include main_color(theme);
			}
		}
		
		.titleRight {
			font-size: 30rpx;
			font-weight: bold;
			color: #282828;
			text-align: center;
			margin: 20rpx 10rpx 36rpx 0;
			position: relative;
			padding-bottom: 30rpx;
			border-bottom: 2rpx solid #f0edf0;
		
			.iconfont {
				position: absolute;
				right: 0;
				top: 0;
				font-size: 30rpx;
			}
		}
	}

	/deep/ .tui-drawer-container_bottom {
		border-radius: 16rpx 16rpx 0 0;
	}
	
	.sku-select {
		.flex-text {
			margin: 8rpx 8rpx;
			background-color: #f7f7f7;
			line-height: 62rpx;
			text-align: center;
			color: #777;
			padding: 16rpx 34rpx;
			font-size: 26rpx;
			font-weight: bolder;
			border-radius: 10rpx;
			border: 1rpx solid #FFF;
		}
	
		.right-class-active {
			@include main_color(theme);
			@include main_bg_rgba_color(theme, 0.05);
			border: 1rpx solid;
		}
	}

	.left-fill-card {
		animation-name: slideInLeft;
		animation-duration: 0.5s;
		animation-fill-mode: both;
	}

	/* 定义动画效果 */
	@keyframes slideInLeft {
		from {
			transform: translateX(-100%);
			opacity: 0;
		}

		to {
			transform: translateX(0);
			opacity: 1;
		}
	}

	.right-fill-card {
		animation-name: slideInRight;
		animation-duration: 0.5s;
		animation-fill-mode: both;
	}

	@keyframes slideInRight {
		from {
			transform: translateX(100%);
			opacity: 0;
		}

		to {
			transform: translateX(0);
			opacity: 1;
		}
	}
</style>